#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 文件: dstversion.py
# 说明:
# 时间: 2021/11/07 15:55:12
# 作者: Azure
# 版本: 1.0

'''获取饥荒最新版本号'''

from re import sub

from lxml import etree
from lxml.etree import _Element
from requests import get
from retry import retry

from .command import SpiderCommand
from .exception import AskurlError


@retry(tries=3)
def __askurl(url: str, par: str):
    '''get html'''
    try:
        res = get(url, headers=SpiderCommand.FAKE_UA, params=par)
        res.encoding = 'utf-8'
        if res.ok:
            return res.content
    except Exception as e:
        raise AskurlError(f'访问 {url} 失败，错误：{e}')


def versioninfo(mode: int):
    '''
    1，仅正式版
    2，仅测试版
    3，全部-list
    4，全部-无标记
    '''
    url = "https://forums.kleientertainment.com/game-updates/dst/"
    html = __askurl(url, par=None)
    tree: _Element = etree.HTML(html)
    __temp_str: list = tree.xpath(
        '//h3[@class="ipsType_sectionHead ipsType_break"]//text()')
    _temp_list = []
    for i in __temp_str:
        i = str(i)
        i = sub(r'[\t \n]', '', i)
        if len(i):
            _temp_list.append(i)

    # print(_temp_list)

    # 转化为字典，为了后续操作方便
    _dict = {}
    for i in range(len(_temp_list)//2):
        try:
            _dict.update({int(_temp_list[i*2]): _temp_list[i*2+1]})
        except:
            # print(f"error: {e}")
            continue

    # print(_dict)

    # 进行排序
    res_list = __sort(_dict)

    # print(res_list)
    res = []
    if mode == 1:
        '''仅正式版'''
        code = 'Release'
    elif mode == 2:
        code = 'Test'
    elif mode == 3:
        return res_list
    elif mode == 4:
        for j in res_list:
            res.append(j[0])
        return res

    for i in res_list:
        if i[1] == code:
            res.append(i[0])
    return res


def __sort(_dict: dict) -> list:
    '''从大到小排序'''
    res = []

    def __inner(__dict: dict):
        if not len(__dict):
            return res
        _i = 0
        for i in __dict.keys():
            if i >= _i:
                _i = i
        res.append([_i, __dict[_i]])
        __dict.pop(_i)
        return __inner(__dict)

    return __inner(_dict)


def newest(mode: int = 1):
    '''
    1.正式版最新版
    2.测试版最新版
    '''

    if mode == 1:
        return versioninfo(1)[0]
    elif mode == 2:
        return versioninfo(2)[0]
    else:
        return None
